package com.hzhc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.common.Constants;
import com.hzhc.common.UserConstants;
import com.hzhc.dto.MetaDto;
import com.hzhc.dto.RouterDto;
import com.hzhc.entity.SysYzsMenu;
import com.hzhc.entity.UserMember;
import com.hzhc.mapper.SysYzsMenuMapper;
import com.hzhc.mapper.UserMemberMapper;
import com.hzhc.service.SysYzsMenuService;
import com.hzhc.vo.SysMenuVo;
import com.hzhc.vo.TreeVo;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dongcy
 * @date 2024/4/12 9:21
 * @description SysYzsMenuServiceImpl
 */
@Service
@RequiredArgsConstructor
public class SysYzsMenuServiceImpl extends ServiceImpl<SysYzsMenuMapper, SysYzsMenu> implements SysYzsMenuService {

    private final Integer PID = 0;

    private final SysYzsMenuMapper sysYzsMenuMapper;

    private final UserMemberMapper userMemberMapper;

    @Override
    public List<SysYzsMenu> getMenuListAll(String name) {
        QueryWrapper<SysYzsMenu> queryWrapper = new QueryWrapper<SysYzsMenu>();
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like("name", name.trim());
        }
        queryWrapper.orderByAsc("type");
        queryWrapper.orderByAsc("parent_id");
        queryWrapper.orderByAsc("order_num");
        return sysYzsMenuMapper.selectList(queryWrapper);
    }

    @Override
    public List<TreeVo> getMlMenuTree(Long valueOf) {
        List<TreeVo> retList = new ArrayList<TreeVo>();
        QueryWrapper<SysYzsMenu> queryWrapper = new QueryWrapper<SysYzsMenu>();
        queryWrapper.eq("type", 0);
        List<SysYzsMenu> list = sysYzsMenuMapper.selectList(queryWrapper);
        Map<Long, List<SysYzsMenu>> menuMap = list.stream().collect(Collectors.groupingBy(SysYzsMenu::getParentId));
        List<SysYzsMenu> glist = menuMap.get(valueOf);
        if(glist!=null){
            getMlMenuTreeList(retList, menuMap, glist);
        }
        return retList;
    }

    @Override
    public List<TreeVo> getMenuTree(Long valueOf) {
        List<TreeVo> retList = new ArrayList<TreeVo>();
        QueryWrapper<SysYzsMenu> queryWrapper = new QueryWrapper<SysYzsMenu>();
        List<SysYzsMenu> list = sysYzsMenuMapper.selectList(queryWrapper);

        Map<Long, List<SysYzsMenu>> menuMap = list.stream().collect(Collectors.groupingBy(SysYzsMenu::getParentId));
        // 是否需要展示最高节点

        List<SysYzsMenu> glist = menuMap.get(valueOf);
        if(glist!=null){
            getMenuTreeList(retList, menuMap, glist);
        }
        return retList;
    }



    @Override
    public boolean saveSysMenu(SysYzsMenu vo) {
        return save(vo);
    }

    @Override
    public boolean updateMenu(SysYzsMenu vo) {
        return updateById(vo);
    }

    private void getMenuTreeList(List<TreeVo> retList, Map<Long, List<SysYzsMenu>> menuMap, List<SysYzsMenu> glist) {
        for (SysYzsMenu menu : glist) {
            TreeVo treeVo = new TreeVo();
            treeVo.setId(menu.getId().intValue());
            treeVo.setLabel(menu.getName());
            treeVo.setChildren(getTreeChildren(menuMap, menu.getId()));
            retList.add(treeVo);
        }
    }

    private void getMlMenuTreeList(List<TreeVo> retList, Map<Long, List<SysYzsMenu>> menuMap, List<SysYzsMenu> glist) {
        for (SysYzsMenu menu : glist) {
            TreeVo treeVo = new TreeVo();
            treeVo.setId(menu.getId().intValue());
            treeVo.setLabel(menu.getName());
            treeVo.setChildren(getTreeChildren(menuMap, menu.getId()));
            retList.add(treeVo);
        }
    }

    private List<TreeVo> getTreeChildren(Map<Long, List<SysYzsMenu>> menuMap, Long id) {
        List<TreeVo> retList = new ArrayList<TreeVo>();
        List<SysYzsMenu> childlist = menuMap.get(id);
        if (childlist != null && !childlist.isEmpty()) {
            getMenuTreeList(retList, menuMap, childlist);
            return retList;
        }
        return null;
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    @Override
    public List<RouterDto> buildMenus(List<SysMenuVo> menus)
    {
        List<RouterDto> routers = new LinkedList<RouterDto>();
        for (SysMenuVo menu : menus)
        {
            RouterDto router = new RouterDto();
            router.setMenuId(menu.getId());
            router.setHidden(menu.getShowStatus()==1);
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
//			router.setQuery(menu.getQuery());
            router.setMeta(new MetaDto(menu.getName(), menu.getIcon(),menu.getShowStatus()==0));
            List<SysMenuVo> cMenus = menu.getChildren();
            if (cMenus != null && !cMenus.isEmpty() && menu.getType() == 0){
                router.setAlwaysShow(true);
                router.setRedirect("");
                router.setChildren(buildMenus(cMenus));
            }else if(menu.getType() == 1){
                //按钮权限
                if (cMenus != null && !cMenus.isEmpty()){
                    List<String> permissionList = cMenus.stream().map(SysMenuVo::getPermission).collect(Collectors.toList());
                    router.setPermissionList(permissionList);
                }
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public List<SysMenuVo> selectMenuTreeByMemberId(Long memberId) {
        List<SysMenuVo> menus = new ArrayList<>();
        UserMember userMember = userMemberMapper.selectById(memberId);
        String code = "";
        if(userMember!=null){
            code =  userMember.getYzsRole();
        }
        //根据用户获取权限菜单
        menus = sysYzsMenuMapper.selectMenuByYzsRole(code);
        return getChildPerms(menus, PID);
    }

    @Override
    public List<SysMenuVo> getSecondRouters(String searchData, Long userId) {
        return sysYzsMenuMapper.selectMenuByMemberIdOrName(searchData,userId);
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    public String getRouteName(SysMenuVo menu){
        String routerName = StringUtils.capitalize(menu.getUrl());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }


    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isMenuFrame(SysMenuVo menu){
        return menu.getParentId().intValue() == PID && menu.getType() == 1;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenuVo menu)
    {
        String routerPath = menu.getUrl();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 1)
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (1 == menu.getParentId().intValue() && menu.getType() == 0)
        {
            routerPath = "/" + menu.getUrl();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach(String path)
    {
        return StringUtils.replaceEach(path, new String[] { Constants.HTTP, Constants.HTTPS, Constants.WWW, "." },
                new String[] { "", "", "", "/" });
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    public String getComponent(SysMenuVo menu)
    {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getModuleUrl()) && !isMenuFrame(menu))
        {
            component = menu.getModuleUrl();
        }
        else if (StringUtils.isEmpty(menu.getModuleUrl()) && menu.getParentId().intValue() != PID)
        {
            component = UserConstants.INNER_LINK;
        }
        else if (StringUtils.isEmpty(menu.getModuleUrl()) && isParentView(menu))
        {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }



    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    public boolean isParentView(SysMenuVo menu)
    {
        return menu.getParentId().intValue() != PID && menu.getType() == 0;
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<SysMenuVo> getChildPerms(List<SysMenuVo> list, int parentId) {
        List<SysMenuVo> returnList = new ArrayList<SysMenuVo>();
        for (SysMenuVo t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn(List<SysMenuVo> list, SysMenuVo t) {
        // 得到子节点列表
        List<SysMenuVo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenuVo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 得到子节点列表
     */
    private List<SysMenuVo> getChildList(List<SysMenuVo> list, SysMenuVo t) {
        List<SysMenuVo> tlist = new ArrayList<>();
        for (SysMenuVo n : list) {
            if (n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenuVo> list, SysMenuVo t) {
        return !getChildList(list, t).isEmpty();
    }

}
